<template>
  <div id="employee">
    <div class="employee-top">
      角色名称：
      <el-input
        style="width: 240px; margin-left: 10px; margin-right: 20px"
        placeholder="请输入角色名称"
        v-model="roleName"
        clearable
      >
      </el-input>

      <el-button type="primary" @click="getList()">查询</el-button>
      <el-button type="primary" @click="dialogFormVisible = true"
        >新增</el-button
      >

      <el-button type="danger">删除</el-button>
      <el-button type="">导出</el-button>
    </div>
    <div class="employee-content">
      <el-table
        :data="tableData"
        border
        style="width: 100%; font-size: 13px; margin-left: 30px"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="150">
        </el-table-column>
        <el-table-column prop="pes" label="权限字符" width="150">
        </el-table-column>

        <el-table-column prop="rid" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="delete scope.row.Id" type="text" size="small"
              >删除</el-button
            >
            <el-button @click="toUpdate(scope.row.rid)" type="text" size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      width="450px"
      top="100px"
      title="新增角色"
      :visible.sync="dialogFormVisible"
    >
      <table>
        <tr>
          <td>角色名称</td>
          <td><el-input v-model="roles.roleName"></el-input></td>
        </tr>
        <br />
        <tr>
          <td>权限字符</td>
          <td><el-input v-model="roles.pes"></el-input></td>
        </tr>
        <tr>
          <td>角色功能</td>
          <td>
            <el-button @click="choose = true">请选择功能</el-button>
            <div v-show="choose">
              <el-tree
                ref="tree"
                :data="treeData"
                :props="defaultProps"
                node-key="id"
                show-checkbox
                check-strictly
                @check-change="handleCheckChange"
              >
              </el-tree>
            </div>
          </td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="450px"
      top="100px"
      title="修改角色"
      :visible.sync="dialogFormVisibled"
    >
      <table>
        <tr>
          <td>角色名称</td>
          <td><el-input v-model="roles.roleName"></el-input></td>
        </tr>
        <br />
        <tr>
          <td>权限字符</td>
          <td><el-input v-model="roles.pes"></el-input></td>
        </tr>
        <tr>
          <td>上级分类</td>
          <td>
            <el-button @click="choose = true">请选择分类</el-button>
            <div v-show="choose">
              <el-tree
                ref="tree"
                :data="treeData"
                :props="defaultProps"
                node-key="id"
                show-checkbox
                check-strictly
                @check-change="handleCheckChange"
              >
              </el-tree>
            </div>
          </td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibled = false">取 消</el-button>
        <el-button type="primary" v-model="roles.rid" @click="update()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "employee",

  data() {
    return {
      treeData: [],
      selectedids: [],
      defaultProps: {
        children: "children",
        label: "name",
        id: "id",
      },

      choose: false,
      roleName: "",
      dialogFormVisible: false,
      dialogFormVisibled: false,
      roles: {
        rid: "",
        roleName: "",
        pes: "",
      },
      tableData: [],
    };
  },
  methods: {
    setCheckedNodes() {
      this.selectedids.forEach((id) => {
        this.findAndCheckNode(this.treeData, id);
      });
    },

    findAndCheckNode(nodes, id) {
      nodes.forEach((node) => {
        if (node.id === id) {
          this.$refs.tree.setChecked(node, true);
        } else if (node.children) {
          this.findAndCheckNode(node.children, id);
        }
      });
    },
    resetTreeSelection() {
      this.$nextTick(() => {
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([]);
        }
      });
    },
    toUpdate(id) {
      this.resetTreeSelection();
      this.selectedids = [];
      this.dialogFormVisibled = true;
      this.axios({
        url: "/info/roleFeature/list",
        params: {
          roleId: id,
        },
      }).then((rs) => {
        rs.data.list.forEach((item) => {
          this.selectedids.push(item.featureId);
        });
        this.setCheckedNodes();
        console.log(this.selectedids);
        this.axios({
          url: "/info/role/list",
          params: {
            rid: id,
          },
        }).then((rs) => {
          this.roles = rs.data.list[0];
        });
      });
    },
    buildTree(data) {
      const tree = [];
      const map = {};
      // 将所有节点添加到map中，方便后续查找
      data.forEach((item) => {
        map[item.id] = { ...item, children: [] };
      });

      // 构建树形结构
      data.forEach((item) => {
        if (item.parentId === 0) {
          tree.push(map[item.id]);
        } else {
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item.id]);
          }
        }
      });

      return tree;
    },
    getFeatures() {
      this.axios({
        url: "/info/feature/list",
      })
        .then((rs) => {
          this.treeData = this.buildTree(rs.data.list);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleCheckChange(node, checked) {
      // 如果节点被勾选
      if (checked) {
        // 设置当前勾选节点的 id
        if (!this.selectedids.includes(node.id)) {
          this.selectedids.push(node.id);
        }
        // 如果是父节点，自动选择所有子节点
        if (node.children && node.children.length > 0) {
          node.children.forEach((childNode) => {
            // 通过 ID 设置子节点为选中状态
            this.$refs.tree.setChecked(childNode.id, true); // 传递 ID
            if (!this.selectedids.includes(childNode.id)) {
              this.selectedids.push(childNode.id); // 确保只有不重复的 ID 被添加
            }
          });
        }
      } else {
        // 如果节点被取消勾选，移除 selectedid 中的当前节点及子节点
        this.selectedids = this.selectedids.filter((item) => item !== node.id);

        // 如果是父节点，取消所有子节点的勾选
        if (node.children && node.children.length > 0) {
          node.children.forEach((childNode) => {
            // 通过 ID 取消子节点的勾选
            this.$refs.tree.setChecked(childNode.id, false); // 传递 ID
            this.selectedids = this.selectedids.filter(
              (item) => item !== childNode.id
            );
          });
        }
      }
    },
    getList() {
      this.axios({
        url: "/info/role/list",
        params: {
          roleName: this.roleName,
        },
      })
        .then((res) => {
          this.getFeatures();
          console.log(res.data);
          this.tableData = res.data.list;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    update() {
      if (!Number.isInteger(this.roles.pes)) {
        alert("权限字符为整数！");
        return;
      }
      var selectedids = JSON.stringify(this.selectedids);
      var roles = JSON.stringify(this.roles);
      var params = new FormData();
      params = {
        selectedids,
        roles,
      };
      this.axios({
        url: "/info/role/update",
        method: "post",
        data: {
          ...params,
        },
      }).then((rs) => {
        console.log(rs.data);
        if (rs.data.isUpdate == true) {
          alert("修改成功");
          this.getList();
          this.dialogFormVisibled = false;
        } else {
          alert("修改失败");
          this.dialogFormVisibled = false;
        }
      });
    },
    save() {
      if (!Number.isInteger(this.roles.pes)) {
        alert("权限字符为整数！");
        return;
      }
      var selectedids = JSON.stringify(this.selectedids);
      var roles = JSON.stringify(this.roles);
      this.dialogFormVisible = true;
      var params = new FormData();
      params = {
        selectedids,
        roles,
      };
      this.axios({
        url: "/info/role/add",
        method: "post",
        data: {
          ...params,
        },
      }).then((rs) => {
        if (rs.data.isAdd === true) {
          alert("增加成功");
          this.getList();
          this.dialogFormVisible = false;
        } else {
          alert("增加失败");
          this.dialogFormVisible = true;
        }
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style scoped>
#employee {
  width: 100%;
  height: 100%;
}

.employee-top {
  width: calc(100% -20px);
  height: 60px;
  /* background-color: pink; */
  line-height: 60px;
  padding-left: 20px;
  font-size: 13px;
}

.employee-content {
  width: 100%;
  height: calc(100% - 60px);
  /* background-color: skyblue; */
}

.el-input,
.el-button {
  font-size: 13px;
}

/* 
  /deep/ .el-dialog {
    height: 600px;
  } */
</style>